package com.faiz.algorithm;

import java.util.Arrays;
import java.util.Random;

//洗牌算法
public class Shuffle {
    private  static final Random RANDOM = new Random();

    public static void shuffle(int[] nums, int n) {
        if (n <= 1) {
            return;
        }
        //产生用于交换的index
        int index = RANDOM.nextInt(n - 1);
//        if (index == 0) {
//            return;
//        }
        //原理就是交换a[0] 和 a[index] ,0<=index<=n-1
        int tmp = nums[0];
        nums[0] = nums[index];
        nums[index] = tmp;
        shuffle(nums, n - 1);
        return;
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5};
        shuffle(nums, nums.length);
        Arrays.stream(nums).forEach(System.out::println);
    }
}
